//
//  LoginViewController.m
//  Contacts
//
//  Created by 李 雷川 on 14-7-14.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "LoginViewController.h"
#import "LoadingView.h"
#import "ResetPasswordViewController.h"
#import "ServerInterface.h"
#import "MainViewController.h"
#import "Contact.h"
#import "ContactDao.h"
#import "Department.h"
#import "DepartmentDao.h"
#import "CompanyDao.h"
#import "Company.h"
#import "JGProgressHUD.h"
#import "UIAlertView+AFNetworking.h"


extern Contact *globalContact;
@interface LoginViewController ()<UITextFieldDelegate>{
    IBOutlet UITextField *nameTextField;
    IBOutlet UITextField *passwordTextField;
    IBOutlet UIButton    *loginBtn;
    IBOutlet UIButton    *forgetPasswordBtn;
    
    __weak IBOutlet UIImageView *headImageView;
    __weak IBOutlet UILabel *nameLabel;
    __weak IBOutlet UILabel *versionLabel;
    JGProgressHUD *HUD;
}
@property(nonatomic, strong) IBOutlet UITextField *nameTextField;
@property(nonatomic, strong) IBOutlet UITextField *passwordTextField;
@property(nonatomic, strong) IBOutlet UIButton    *loginBtn;
@property(nonatomic, strong) IBOutlet UIButton    *forgetPasswordBtn;
@end

@implementation LoginViewController
@synthesize nameTextField,passwordTextField;
@synthesize loginBtn,forgetPasswordBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.title = @"登录";
    [headImageView setClipsToBounds:YES];
    [headImageView.layer setBorderColor:[UIColor colorWithRed:255 green:255 blue:255 alpha:1.0].CGColor];
    [headImageView.layer setBorderWidth:2.0];
    [headImageView.layer setCornerRadius:headImageView.frame.size.width/2.0];
    
    
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey];
    versionLabel.text = version;
    if (globalContact) {
        MainViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];
        [self.navigationController pushViewController:viewController animated:NO
         ];
        
    }
//    LoadingView *loadingView = [[LoadingView alloc]initWithFrame:self.view.frame];
//    [self.view addSubview:loadingView];
//    __weak LoadingView *view = loadingView;
//    view.finishAnimationBlock = ^(){
//        [UIView animateWithDuration:1.0 animations:^{
//            view.alpha = 0.0;
//        } completion:^(BOOL finished) {
//             [view removeFromSuperview];
//        }];
//    };

//    [loginBtn setImage:[UIImage imageNamed:@"login_s.png"] forState:UIControlStateHighlighted];
}

-(void)viewWillAppear:(BOOL)animated{
   [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (globalContact) {
        nameTextField.text = globalContact.loginName;
        nameLabel.text = globalContact.name;
        passwordTextField.text = globalContact.password;
        NSString *fullImagePath = [IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName];
        if ([[NSFileManager defaultManager]fileExistsAtPath:fullImagePath]) {
            headImageView.image =[UIImage imageWithContentsOfFile:fullImagePath];
        }
      
    }
}
-(void)viewDidAppear:(BOOL)animated{
//    self.navigationController.navigationBar.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(IBAction)forgetPassword:(id)sender{
    
}

-(IBAction)login:(id)sender{
    if (nameTextField.text.length == 0 || passwordTextField.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:@"用户名或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [nameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    
    HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleLight];
    HUD.textLabel.text = @"正在登录";
    [HUD showInView:self.view animated:YES];
    NSDictionary *loginDic = @{@"user_name":nameTextField.text,@"password":passwordTextField.text,@"company_id":CompanyID};
    [ServerInterface loginWithInfoDic:loginDic withBlock:^(NSDictionary *resultDic, NSError *error) {
        if (error) {
            NSLog(@"error is:%@",error);
            HUD.textLabel.text = @"连接服务器失败";
        }
        else{
            if ([[resultDic valueForKeyPath:@"success"] integerValue] ==1) {
                NSDictionary *dic = [resultDic valueForKeyPath:@"data"];
                [[NSUserDefaults standardUserDefaults]setObject:dic[@"id"] forKey:@"userID"];
                [[NSUserDefaults standardUserDefaults]setObject:dic[@"token"] forKey:@"token"];
                Contact *contact = [Contact  analysisUserInfoDic:dic];
                contact.password = passwordTextField.text;
                contact.loginName = nameTextField.text;
                [self saveToDBWithContact:contact];
                globalContact = contact;
                [self updateHeadWithContact:contact success:^{
                    NSLog(@"success");
                    if (contact.isActivity) {
                        [self enterMainViewController];
                    }
                    else{
                        [self enterResetPassword];
                    }
                }];
                
            }
            else{
                NSString *message =[resultDic objectForKey:@"message"];
//                HUD.textLabel.text = message;
//                sleep(2.0);
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                
                NSLog(@"message is:%@",message);
            }
        }
       [HUD dismissAfterDelay:1.0];
    }];


}

-(void)updateHeadWithContact:(Contact *)contact success:(void (^)(void))block{
    if ([contact.headUrl hasSuffix:@"png"] ||[contact.headUrl hasSuffix:@"jpg"]) {
        if ( [globalContact.headName isEqualToString:contact.headName] == NO) {
            NSString *fullImagePath = [IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName];
            if ([[NSFileManager defaultManager]fileExistsAtPath:fullImagePath]) {
                headImageView.image =[UIImage imageWithContentsOfFile:fullImagePath];
                if (block) {
                    block();
                }
            }
            else{
                __weak UIImageView *imageView = headImageView;
                [headImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:contact.headUrl]]  placeholderImage: [UIImage imageNamed:@"logo.png"]  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                    imageView.image = image;
                    NSString *filePath =[IMAGE_FORDER stringByAppendingPathComponent:globalContact.headName];
                    if (![[NSFileManager defaultManager] fileExistsAtPath:IMAGE_FORDER isDirectory:nil]) {
                        [[NSFileManager defaultManager]createDirectoryAtPath:IMAGE_FORDER withIntermediateDirectories:YES attributes:nil error:nil];
                    }
                    BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                    if (success) {
                        
                    }
                    if (block) {
                        block();
                    }
                } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                    if (block) {
                        block();
                    }
                }];
            }
        }
        else {
            if (block) {
                block();
            }
        }
    }
}

-(void)enterMainViewController{
    MainViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];
    [self.navigationController pushViewController:viewController animated:YES
     ];
    
//    NSString* deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];
//    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
//    //----登录server----//
//    [RCIM initWithAppKey:RongYun_AppKey deviceToken:(deviceToken==nil)?@"":deviceToken];
//    [RCIM connectWithToken:globalContact.token delegate:self];
//    [RCIM setFriendsFetcherWithDelegate:self];
//    [RCIM setUserInfoFetcherWithDelegate:self isCacheUserInfo:NO];
}

-(void)enterResetPassword{
    ResetPasswordViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ResetPasswordViewController"];
    [self.navigationController pushViewController:viewController animated:YES
     ];
}
-(BOOL)saveToDBWithContact:(Contact *)contact{
    BOOL success;
    if (globalContact && globalContact.userID == contact.userID) {
       success = [Contact updateContact:contact] &&[Company updateCompany:contact.company];
       ;
    }
    else{
        success = [Contact saveContact:contact] &&  [Company saveCompany:contact.company];
    }
    return success;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (touch.tapCount == 1) {
        [self.nameTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
    }
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self login:nil];
    if (nameTextField.text.length == 0 || passwordTextField.text.length == 0) {
        return NO;
    }
    
    [nameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    return YES;
}


@end
